package com.example.webcourse

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.webkit.SslErrorHandler
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebView.HitTestResult
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.webcourse.bean.MessageEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.Stack


class MainActivity : AppCompatActivity() {
    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        EventBus.getDefault().register(this)
        val webView = findViewById<WebView>(R.id.webView)
        webView.settings.javaScriptEnabled = true
        webView.webViewClient = MyWebViewClient()
        webView.loadUrl("https://jw.gdou.edu.cn/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default")
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onMessageEvent(event: MessageEvent) {
        Toast.makeText(this, event.getMessage(), Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    class MyWebViewClient() : WebViewClient() {
        /**
         * 返回栈
         */
        private val mUrls = Stack<String>()

        /**
         * 记录操作路径的url临时栈
         */
        private val mTempUrls: List<String> = ArrayList()

        /**
         * 判断页面是否加载完成
         */
        private val mIsLoading = false
        private var mShowingUrl: String? = null
        private var mUrlBeforeRedirect: String? = null
        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            Log.e("onPageStarted", "url:$url")
            recordUrl(url)
            //this.mIsLoading = true;
        }

        /**
         * 记录非重定向链接, 避免刷新页面造成的重复入栈
         *
         * @param url 链接
         */
        private fun recordUrl(url: String) {
            //这里还可以根据自身业务来屏蔽一些链接被放入URL栈
            mShowingUrl = url
            if (!TextUtils.isEmpty(url) && !url.equals(lastPageUrl, ignoreCase = true)) {
                if (!(url.startsWith("http") || url.startsWith("https"))) {
                    return
                }
                if (!TextUtils.isEmpty(mUrlBeforeRedirect) && mUrlBeforeRedirect == url) { //重定向的url屏蔽
                    mUrlBeforeRedirect = null
                    return
                }
                mUrls.push(url)
            }
        }

        @get:Synchronized
        private val lastPageUrl: String?
            /**
             * 获取上一页的链接
             */
            get() = if (mUrls.size > 0) mUrls.peek() else null

        /**
         * 推出上一页链接
         */
        fun popLastPageUrl(): String? {
            if (mUrls.size >= 2) {
                mUrls.pop() //当前url
                return mUrls.pop()
            }
            return null
        }

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            view.settings.blockNetworkImage = false
            Log.e("onPageFinished", "url:$url")
        }

        override fun onReceivedSslError(
            webView: WebView, sslErrorHandler: SslErrorHandler,
            sslError: SslError
        ) {
            //super.onReceivedSslError(webView, sslErrorHandler, sslError);
            sslErrorHandler.proceed() // 接受所有网站的证书
        }

        @SuppressLint("LongLogTag")
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            Log.e("shouldUrlLoading", "url:$url")
            return if (url.startsWith("tel:")) {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                (intent)
                true
            } else {
                if (!(url.startsWith("http") || url.startsWith("https"))) {
                    return true
                }
                val hitTestResult = view.hitTestResult
                val hitType = hitTestResult.type
                if (hitType != HitTestResult.UNKNOWN_TYPE) {
                    Log.e("WebViewManger", "没有进行重定向操作")
                    //这里执行自定义的操作
                    view.loadUrl(url)
                    true
                } else {
                    EventBus.getDefault().post(MessageEvent("请先登录"))
                    Log.e("WebViewManger", "进行了重定向操作")
                    mUrlBeforeRedirect = url
                    //重定向时hitType为0 ,执行默认的操作
                    false
                }
            }
        }

        override fun shouldInterceptRequest(
            view: WebView,
            request: WebResourceRequest
        ): WebResourceResponse? {
//            request.url.toString()
            Log.d("kkkkkk",request.url.toString())
            return super.shouldInterceptRequest(view, request)
        }
    }
}